<template>
  <view>
	  <u-button id="shareBtn" open-type="share" ></u-button>
    <!-- 在这里展示要分享的内容 -->
    <image :src="imageUrl"></image>
    <text>{{ title }}</text>
    
    <!-- 生成海报 -->
    <canvas canvas-id="myCanvas"></canvas>
    
    <!-- 预览和下载海报 -->
    <image :src="posterUrl" mode="widthFix" @click="previewPoster"></image>
    <button type="primary" @click="downloadPoster">下载海报</button>
	
  </view>
</template>

<script>
  export default {
    data() {
      return {
        imageUrl: 'https://example.com/image.png', // 要分享的图片链接
        title: '这是要分享的标题', // 要分享的文本内容
        posterUrl: '', // 生成的海报链接
        canvasWidth: 375, // canvas宽度
        canvasHeight: 600 // canvas高度
      }
    },
    methods: {
      // 生成海报
      createPoster() {
        // 获取canvas上下文
        const ctx = uni.createCanvasContext('myCanvas', this);
        // 绘制背景
        ctx.fillStyle = '#fff';
        ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight);
        // 绘制图片
        ctx.drawImage(this.imageUrl, 0, 0, this.canvasWidth, this.canvasHeight);
        // 绘制文本
        ctx.fillStyle = '#000';
        ctx.font = 'bold 32px Arial';
        ctx.fillText(this.title, 50, 500);
        // 保存canvas图片，并获取链接
        ctx.draw(false, () => {
          uni.canvasToTempFilePath({
            canvasId: 'myCanvas',
            success: (res) => {
              this.posterUrl = res.tempFilePath;
            }
          }, this);
        });
      },
      // 预览海报
      previewPoster() {
        uni.previewImage({
          current: this.posterUrl,
          urls: [this.posterUrl]
        });
      },
      // 下载海报
      downloadPoster() {
        uni.downloadFile({
          url: this.posterUrl,
          success: (res) => {
            uni.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: () => {
                uni.showToast({
                  title: '保存成功'
                });
              },
              fail: () => {
                uni.showToast({
                  title: '保存失败',
                  icon: 'none'
                });
              }
            });
          }
        });
      }
    },
    mounted() {
      this.createPoster();
    }
  }
</script>

